%real time remove background
clc,clear
mode=2;
YearMonthDay=20190624;
addpath(genpath('\\calcenter2\Rb87ProgramBEC3\removeBackground\'));
folderName=['\\RB87BEC2\ShareFolder\' num2str(YearMonthDay) 'morning\ikon-22860\'];
% folderName=['E:\DataBackup\' num2str(YearMonthDay) 'morning\ikon-22860\'];
saveFolder=['\\calcenter2\oriData\' num2str(YearMonthDay) '\'];
mkdir(saveFolder);
photoNamePre='22860test_';
filename_pre='ascOD22860test_';
refimagesIniDirectory='\\calcenter2\Rb87ProgramBEC3\removeBackground\backgrounddata\refimagesIni_22860new.mat';
% addpath(genpath('ExperimentBasicFunction'));
%if pictures includes 3 images,mode='3picture',else mode='1picture'
figuremode='1picture';
% h1=figure(1);h2=figure(2);
%initial------------------------------------------------------------
overWrite=0;
refNum=250;
checkCycle=0.001;%second
%%������������������������������������������������������������������������������������������������
photoStart=018;
%%������������������������������������������������������������������������������������������������
removeBG=1;

bgmask2=ones(1024,1024);
bgmask3=-ones(1024,1024);
bgmask1=zeros(1024,1024);
rectangle_FWHM=150;

%--------------------------------------------------------------------------
%find center of atoms
% initial radial of region of cloud
radial0=70;
%edge value of atom cloud:edge0(1),find edge;edge0(2),define edge and final region of atoms cloud
edge0=[0.05 0.05];
%number of cloud in a picture
cloudofnumber=2;
%scan region
x_initial=80;
y_initial=80;
x_final=800;
y_final=800;
%adjacent scan displacement
scan_displacement=10;
%distance between scanning circle and maxium of inside circle
distance=2;
%--------------------------------------------------------------------------

% refimagesIni(:,:,210)=refCreate(13,'bg','E:\�׳���\Rb87Files\20161205morning\ikon_22860\','22860test_',1024);
%load reference images
refimagesIniStruct=load(refimagesIniDirectory);
refimagesIni=refimagesIniStruct.refimagesIni;

if size(refimagesIni,3)==refNum
    refimages=refimagesIni;
else
    error('Error: refNum ~= loaded reference images');
end
if mode==2
    cd(folderName);
    newestDatenum=0;
    photoInd=photoStart;
    
    while(true)
        savefilename= photoName(saveFolder,photoNamePre,photoInd,'od.mat');
        if exist(photoName(folderName,photoNamePre,photoInd,'nolight.asc'),'file')
            try
%             if exist(photoName(folderName,photoNamePre,photoInd,'.asc'),'file')
                files_if=[photoInd photoInd];
                [image]=drawpicture(folderName,filename_pre,files_if,figuremode);
%                 figure(1);
%                 set(0,'CurrentFigure',h1);
%                 clf reset;
%                 imagesc(image(1).data,[-0.1,0.5]);title(num2str(photoInd));
                %change ROI and ROI1 by auto------------------------------------
                if removeBG==1
%                 [xpeak,ypeak,radial_cloud,image_size,average_background]=clouds_region(image,radial0,edge0,cloudofnumber,x_initial,y_initial,x_final,y_final,scan_displacement,distance);
%                 if isempty(xpeak{1,1})
%                     photoInd=photoInd+1;
%                     [odim]=drawpicture(folderName,filename_pre,files_if,'1picture');
%                     odimage=odim.data;
%                     save(savefilename,'odimage');
%                     continue;
%                 end
                xminROI1=70;yminROI1=130;
                xmin=60;ymin=160;rectangle_width=550;rectangle_height=500;
%                 [ROI ROI1]=rangeofinterest(xpeak{1,1},ypeak{1,1},radial_cloud{1,1},rectangle_FWHM,xminROI1,yminROI1);
                %---------------------------------------------------------
                %change ROI and ROI1 by manual
                ROI=[xmin,ymin,rectangle_width,rectangle_height];
                 ROI1=[xminROI1-30,yminROI1-30,800,800];
                ROIX_vector=ROI(1):(ROI(1)+ROI(3));
                ROIY_vector=ROI(2):(ROI(2)+ROI(4));
                ROIX_vector1=ROI1(1):(ROI1(1)+ROI1(3));
                ROIY_vector1=ROI1(2):(ROI1(2)+ROI1(4));
                bgmask3(ROIY_vector,ROIX_vector)=-2;
                bgmask1(ROIY_vector1,ROIX_vector1)=1;
                bgmask=bgmask1+bgmask2+bgmask3;
%                 figure(10),imagesc(bgmask);
%             end
            if overWrite==0 && exist(photoName(folderName,photoNamePre,photoInd,'od.mat'),'file')==2
                disp([photoName(folderName,photoNamePre,photoInd,'od.mat') ' already exist, skip it']);
                photoInd=photoInd+1;
                continue;
            end
            absimages=loadPhoto(photoName(folderName,photoNamePre,photoInd,'.asc'));
            refimages(:,:,mod(photoInd,refNum)+1)=loadPhoto(photoName(folderName,photoNamePre,photoInd,'bg.asc'));
            nolimage=loadPhoto(photoName(folderName,photoNamePre,photoInd,'nolight.asc'));
%             figure(4);imagesc(refimages(:,:,mod(photoInd,refNum)+1));
%             figure(5);imagesc(absimages);
%             figure(6);imagesc(nolimage);
            
            %calculate
            refimageCal=fringeremoval(absimages,refimages,bgmask);
            refimageCalMNolight=((refimageCal-nolimage)+abs(refimageCal-nolimage))/2+1;
            absimageMNolight=((absimages-nolimage)+abs(absimages-nolimage))/2+1;
            odimage=log(  refimageCalMNolight./absimageMNolight  );
            
%             figure(2);
% %             set(0,'CurrentFigure',h2);
% %             clf reset;
%             imagesc(odimage,[-0.1,0.5]);
%             title(photoName(folderName,photoNamePre,photoInd,''));
%             rectangle('position',ROI);

            %             rectangle('position',atomSumRange);
%             atomX=atomSumRange(1):(atomSumRange(1)+atomSumRange(3));
%             atomY=atomSumRange(2):(atomSumRange(2)+atomSumRange(4));
%             atomCut=odimage(atomY,atomX);
%             atomSum=pixelWidth*pixelWidth*10/sigma_cross*sum(sum(atomCut));
%             text(400,100,['N=' num2str(atomSum,'%10.3e')], 'BackgroundColor','w');
            
            savefilename= photoName(saveFolder,photoNamePre,photoInd,'od.mat');
            save(savefilename,'odimage');
                end 
            %incase the program is interrupted
%             save(refimagesIniDirectory,'refimagesIni');
            %                     fprintf( '%s\n\n', [newPhotoNamePre ' calculate finished, refimages saved'] );
            
            photoInd=photoInd+1;
            catch ME
                disp(ME.identifier);
                pause(checkCycle);
            end
%         else
            
            pause(checkCycle);
        end
        
        savefilename= photoName(saveFolder,photoNamePre,photoInd,'od.mat');
        if exist(photoName(folderName,photoNamePre,photoInd,'nolight.asc'),'file')
            try
%             if exist(photoName(folderName,photoNamePre,photoInd,'.asc'),'file')
                files_if=[photoInd photoInd];
                [image]=drawpicture(folderName,filename_pre,files_if,figuremode);
%                 figure(1);
%                 set(0,'CurrentFigure',h1);
%                 clf reset;
%                 imagesc(image(1).data,[-0.1,0.5]);title(num2str(photoInd));
                %change ROI and ROI1 by auto------------------------------------
                if removeBG==1
                [xpeak,ypeak,radial_cloud,image_size,average_background]=clouds_region(image,radial0,edge0,cloudofnumber,x_initial,y_initial,x_final,y_final,scan_displacement,distance);
                if isempty(xpeak{1,1})
                    photoInd=photoInd+1;
                    [odim]=drawpicture(folderName,filename_pre,files_if,'1picture');
                    odimage=odim.data;
                    save(savefilename,'odimage');
                    continue;
                end
                xminROI1=70;yminROI1=130;
                xmin=60;ymin=160;rectangle_width=550;rectangle_height=500;
%                 [ROI ROI1]=rangeofinterest(xpeak{1,1},ypeak{1,1},radial_cloud{1,1},rectangle_FWHM,xminROI1,yminROI1);
                %---------------------------------------------------------
                %change ROI and ROI1 by manual
                ROI=[xmin,ymin,rectangle_width,rectangle_height];
                 ROI1=[xminROI1-30,yminROI1-30,800,800];
                ROIX_vector=ROI(1):(ROI(1)+ROI(3));
                ROIY_vector=ROI(2):(ROI(2)+ROI(4));
                ROIX_vector1=ROI1(1):(ROI1(1)+ROI1(3));
                ROIY_vector1=ROI1(2):(ROI1(2)+ROI1(4));
                bgmask3(ROIY_vector,ROIX_vector)=-2;
                bgmask1(ROIY_vector1,ROIX_vector1)=1;
                bgmask=bgmask1+bgmask2+bgmask3;
%                 figure(10),imagesc(bgmask);
%             end
            if overWrite==0 && exist(photoName(folderName,photoNamePre,photoInd,'od.mat'),'file')==2
                disp([photoName(folderName,photoNamePre,photoInd,'od.mat') ' already exist, skip it']);
                photoInd=photoInd+1;
                continue;
            end
            absimages=loadPhoto(photoName(folderName,photoNamePre,photoInd,'.asc'));
            refimages(:,:,mod(photoInd,refNum)+1)=loadPhoto(photoName(folderName,photoNamePre,photoInd,'bg.asc'));
            nolimage=loadPhoto(photoName(folderName,photoNamePre,photoInd,'nolight.asc'));
%             figure(4);imagesc(refimages(:,:,mod(photoInd,refNum)+1));
%             figure(5);imagesc(absimages);
%             figure(6);imagesc(nolimage);
            
            %calculate
            refimageCal=fringeremoval(absimages,refimages,bgmask);
            refimageCalMNolight=((refimageCal-nolimage)+abs(refimageCal-nolimage))/2+1;
            absimageMNolight=((absimages-nolimage)+abs(absimages-nolimage))/2+1;
            odimage=log(  refimageCalMNolight./absimageMNolight  );
            
%             figure(2);
% %             set(0,'CurrentFigure',h2);
% %             clf reset;
%             imagesc(odimage,[-0.1,0.5]);
%             title(photoName(folderName,photoNamePre,photoInd,''));
%             rectangle('position',ROI);

            %             rectangle('position',atomSumRange);
%             atomX=atomSumRange(1):(atomSumRange(1)+atomSumRange(3));
%             atomY=atomSumRange(2):(atomSumRange(2)+atomSumRange(4));
%             atomCut=odimage(atomY,atomX);
%             atomSum=pixelWidth*pixelWidth*10/sigma_cross*sum(sum(atomCut));
%             text(400,100,['N=' num2str(atomSum,'%10.3e')], 'BackgroundColor','w');
            
            savefilename= photoName(saveFolder,photoNamePre,photoInd,'od.mat');
            save(savefilename,'odimage');
                end 
            %incase the program is interrupted
%             save(refimagesIniDirectory,'refimagesIni');
            %                     fprintf( '%s\n\n', [newPhotoNamePre ' calculate finished, refimages saved'] );
            
            photoInd=photoInd+1;
            catch ME
                disp(ME.identifier);
                pause(checkCycle);
            end
        else
            
            pause(checkCycle);
        end
    end
end
save(refimagesIniDirectory,'refimagesIni');